﻿using FileSecretAssemblyStandard;
using Ldt.DataEngin.PCPackage.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;

namespace Ldt.DataEngin.PCPackage
{
  public class WordParseConfigFileCommon
  {
    private string rootPathConfig = string.Empty;

    public WordParseConfigFileCommon(string configPath)
    {
      this.rootPathConfig = Path.Combine(configPath, "config", "wordparse2.0");
    }

    public string GeyProcessFileName(
      string caseType,
      string docID,
      string appId = null,
      string courtId = null,
      string caseCause = null)
    {
      string str1 = "default";
      string str2 = Path.Combine(new string[4]
      {
        this.rootPathConfig,
        "config",
        "processConfig",
        "analysisprocessconfig"
      });
      List<string> stringList = new List<string>();
      if (!string.IsNullOrEmpty(appId))
        stringList.Add(appId);
      if (!string.IsNullOrEmpty(courtId))
        stringList.Add(courtId);
      if (!string.IsNullOrEmpty(caseCause))
        stringList.Add(caseCause);
      if (stringList.Count > 0)
      {
        foreach (string str3 in stringList)
          str1 = !(str1.ToLower() == "default") ? str1 + "_" + str3 : str3;
      }
      string str4 = str1 + ".xml";
      string path = Path.Combine(new string[4]
      {
        str2.ToLower(),
        caseType.ToLower(),
        docID.ToLower(),
        str4.ToLower()
      });
      Ldt.DataEngine.LogHandle.LogHandle.GetInitLogHandle.LogWrite("GetConfigInfo接口：得到流程配置文件的path是" + path);
      if (str4.ToLower() != "default.xml" && !File.Exists(path))
      {
        Ldt.DataEngine.LogHandle.LogHandle.GetInitLogHandle.LogWrite("GetConfigInfo接口：流程配置文件" + path + "不存在，获取默认文件。" + Environment.NewLine);
        path = Path.Combine(new string[4]
        {
          str2.ToLower(),
          caseType.ToLower(),
          docID.ToLower(),
          "default.xml"
        });
      }
      return path;
    }

    public ModuleConfig GetProcessFileInfo(string processFile, ref XmlNode rootNode)
    {
      string content = FileSecretFactory.GetFileSecretInstance((FileSecretFactory.FileSecretType) 0).DecryptFileToContent(processFile);
      XmlDocument xmlDocument = new XmlDocument();
      xmlDocument.LoadXml(content);
      XmlNodeList xmlNodeList = xmlDocument.SelectNodes("/root");
      rootNode = xmlNodeList[0];
      Ldt.DataEngine.LogHandle.LogHandle.GetInitLogHandle.LogWrite("GetConfigInfo接口：开始加密流程配置文件内容，未加密前=" + rootNode.OuterXml);
      string directoryName = Path.GetDirectoryName(processFile);
      ModuleConfig moduleConfig1 = new ModuleConfig();
      moduleConfig1.number = "0";
      moduleConfig1.moduleName = "流程配置文件";
      string[] strArray1 = directoryName.Replace("/", "\\").Split(new string[1]
      {
        "\\config\\"
      }, StringSplitOptions.None);
      ModuleConfig moduleConfig2 = moduleConfig1;
      string[] strArray2 = new string[3]
      {
        "config",
        null,
        null
      };
      string[] strArray3 = strArray1;
      strArray2[1] = strArray3[strArray3.Length - 1].Trim('\\');
      strArray2[2] = Path.GetFileNameWithoutExtension(processFile) + ".xml";
      string str = Path.Combine(strArray2).Replace("/", "\\");
      moduleConfig2.filePath = str;
      moduleConfig1.executeCode = Path.GetFileName(processFile);
      moduleConfig1.executeType = "file";
      moduleConfig1.code = "ProcessConfig";
      moduleConfig1.configContent = rootNode.OuterXml;
      return moduleConfig1;
    }

    public ModuleConfig GetModuleConfigInfo(XmlNode moduleNode)
    {
      InterfaceFileSecret fileSecretInstance = FileSecretFactory.GetFileSecretInstance((FileSecretFactory.FileSecretType) 0);
      string str1 = moduleNode.Attributes["executefile"].Value;
      if (str1.StartsWith("\\"))
        str1 = str1.Substring(1);
      string fileFullName = Path.Combine(this.rootPathConfig, str1.Replace("\\", "/").ToLower());
      string str2 = moduleNode.Attributes["zh_cn"].Value;
      ModuleConfig moduleConfig1 = new ModuleConfig();
      moduleConfig1.number = moduleNode.Attributes["number"].Value;
      moduleConfig1.moduleName = str2;
      moduleConfig1.code = moduleNode.Attributes["code"].Value;
      moduleConfig1.executeType = moduleNode.Attributes["executetype"].Value;
      moduleConfig1.executeCode = moduleNode.Attributes["executecode"].Value;
      moduleConfig1.filePath = moduleNode.Attributes["executefile"].Value.ToLower().Trim('\\').Replace("/", "\\");
      Ldt.DataEngine.LogHandle.LogHandle.GetInitLogHandle.LogWrite("GetConfigInfo接口：读取流程配置文件中的'" + str2 + "'模块的配置文件" + fileFullName);
      string fileName = this.GetFileName(fileFullName);
      if (fileName != "notfound")
      {
        XmlDocument moduleConfig2 = new XmlDocument();
        try
        {
          string content = fileSecretInstance.DecryptFileToContent(fileName);
          moduleConfig2.LoadXml(content);
        }
        catch (Exception ex)
        {
          Ldt.DataEngine.LogHandle.LogHandle.GetInitLogHandle.LogWrite("GetConfigInfo接口：load'" + str2 + "'模块的配置文件" + fileName + "错误!" + ex.Message);
        }
        int num = 0;
        XmlNodeList xmlNodeList = moduleConfig2.SelectNodes("/root");
        moduleConfig1.mlflag = xmlNodeList[0].Attributes["mlflag"] != null ? xmlNodeList[0].Attributes["mlflag"].Value : "0";
        foreach (XmlNode childNode in xmlNodeList[0].ChildNodes)
        {
          if (childNode.NodeType != XmlNodeType.Comment)
          {
            if (childNode.Attributes["executetype"].Value == "xml")
            {
              num = 1;
              break;
            }
            num = 0;
          }
        }
        if (num == 1)
        {
          moduleConfig1.configDetail = new List<ModuleConfig>();
          moduleConfig1.configDetail = this.parseXmlMoudleConfig(moduleConfig2, moduleConfig1.moduleName, fileName).OrderBy<ModuleConfig, string>((Func<ModuleConfig, string>) (a => a.number)).ToList<ModuleConfig>();
        }
        moduleConfig1.configContent = moduleConfig2.OuterXml;
        Ldt.DataEngine.LogHandle.LogHandle.GetInitLogHandle.LogWrite("GetConfigInfo接口：读取与加密'" + moduleConfig1.moduleName + "'模块的配置文件" + fileName + "完成!");
      }
      else
      {
        moduleConfig1.configContent = "";
        Ldt.DataEngine.LogHandle.LogHandle.GetInitLogHandle.LogWrite("GetConfigInfo接口：" + moduleConfig1.moduleName + "模块的配置文件" + fileName + "不存在!");
      }
      return moduleConfig1;
    }

    private List<ModuleConfig> parseXmlMoudleConfig(
      XmlDocument moduleConfig,
      string moduleName,
      string moduleConfigPath)
    {
      List<ModuleConfig> parsedConfigs = new List<ModuleConfig>();
      string fullName = new FileInfo(moduleConfigPath).Directory.FullName;
      foreach (XmlNode childNode in moduleConfig.SelectNodes("/root")[0].ChildNodes)
      {
        if (childNode.Attributes["executetype"].Value == "xml")
          this.parseStepNode(childNode, fullName, (ModuleConfig) null, parsedConfigs);
      }
      return parsedConfigs;
    }

    private void parseStepNode(
      XmlNode stepNode,
      string dirp,
      ModuleConfig parentNode,
      List<ModuleConfig> parsedConfigs)
    {
      ModuleConfig moduleConfig = new ModuleConfig();
      moduleConfig.number = stepNode.Attributes["number"] != null ? stepNode.Attributes["number"].Value : "";
      moduleConfig.moduleName = stepNode.Attributes["zh_cn"] != null ? stepNode.Attributes["zh_cn"].Value : "";
      moduleConfig.code = stepNode.Attributes["code"] != null ? stepNode.Attributes["code"].Value : "";
      moduleConfig.executeType = stepNode.Attributes["executetype"] != null ? stepNode.Attributes["executetype"].Value : "";
      moduleConfig.executeCode = stepNode.Attributes["executecode"] != null ? stepNode.Attributes["executecode"].Value : "";
      if (stepNode.Attributes["executefile"] == null)
      {
        moduleConfig.filePath = "";
      }
      else
      {
        string str = stepNode.Attributes["executefile"].Value.ToLower().Trim('\\').Replace("/", "\\");
        if (str.IndexOf("\\wordparse2.0\\") > -1)
          moduleConfig.filePath = str.Split(new string[1]
          {
            "\\wordparse2.0\\"
          }, StringSplitOptions.None)[1].Trim('\\');
        else
          moduleConfig.filePath = str;
      }
      string fileName = this.GetFileName(Path.Combine(this.rootPathConfig, moduleConfig.filePath).ToLower());
      Ldt.DataEngine.LogHandle.LogHandle.GetInitLogHandle.LogWrite("parseStepNodee:GetFileName=" + fileName);
      if (moduleConfig.executeType == "xml")
      {
        XmlDocument xmlDocument = new XmlDocument();
        if (!fileName.Contains("notfound"))
        {
          try
          {
            string content = FileSecretFactory.GetFileSecretInstance((FileSecretFactory.FileSecretType) 0).DecryptFileToContent(fileName);
            xmlDocument.LoadXml(content);
            Ldt.DataEngine.LogHandle.LogHandle.GetInitLogHandle.LogWrite("parseStepNodee接口:结构化xml文件" + content);
          }
          catch (Exception ex)
          {
            Ldt.DataEngine.LogHandle.LogHandle.GetInitLogHandle.LogWrite("parseStepNodee接口:发生异常" + ex.Message);
          }
          moduleConfig.configContent = xmlDocument.OuterXml;
        }
        else
          moduleConfig.configContent = string.Empty;
      }
      if (parentNode == null)
      {
        parentNode = moduleConfig;
      }
      else
      {
        if (parentNode.configDetail == null)
          parentNode.configDetail = new List<ModuleConfig>();
        parentNode.configDetail.Add(moduleConfig);
      }
      foreach (XmlNode childNode in stepNode.ChildNodes)
        this.parseStepNode(childNode, dirp, parentNode, parsedConfigs);
      if (parsedConfigs.FindIndex((Predicate<ModuleConfig>) (a => a.number == parentNode.number)) >= 0)
        parsedConfigs.Remove(parentNode);
      parsedConfigs.Add(parentNode);
    }

    private string EnCodeBase64(int codepage, string decode)
    {
      string str;
      try
      {
        str = Convert.ToBase64String(Encoding.GetEncoding(codepage).GetBytes(decode));
      }
      catch
      {
        str = "";
      }
      return str;
    }

    public string GetFileName(string fileFullName)
    {
      string extension = Path.GetExtension(fileFullName);
      string withoutExtension = Path.GetFileNameWithoutExtension(fileFullName);
      string directoryName = Path.GetDirectoryName(fileFullName);
      string path = string.Empty;
      if (extension == ".xml")
        path = Path.Combine(directoryName, withoutExtension + ".xmlldt");
      if (extension == ".xmlldt")
        path = Path.Combine(directoryName, withoutExtension + ".xml");
      if (extension == ".json")
        path = Path.Combine(directoryName, withoutExtension + ".jsonldt");
      if (extension == ".jsonldt")
        path = Path.Combine(directoryName, withoutExtension + ".json");
      Ldt.DataEngine.LogHandle.LogHandle.GetInitLogHandle.LogWrite("otherFileName=" + path);
      if (File.Exists(fileFullName))
        return fileFullName;
      if (File.Exists(path))
        return path;
      return "notfound";
    }
  }
}
